import enums.ResponseType;
import request.relation.FriendAddDecisionRequest;
import response.ErrorResponse;
import response.Response;
import response.relation.FriendAddDecisionResponse;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FriendApplicationHandler implements ActionListener {
    private FriendApplicationView friendApplicationView;

    public FriendApplicationHandler(FriendApplicationView friendApplicationView) {
        this.friendApplicationView = friendApplicationView;
    }

    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("同意".equals(text)) {
            agree(friendApplicationView.getGuestUserName(), friendApplicationView.getHostUserName());
        } else if ("拒绝".equals(text)) {
            disagree(friendApplicationView.getGuestUserName(), friendApplicationView.getHostUserName());
        }
    }

    public void agree(String hostUserName, String guestUserName) {
        FriendAddDecisionRequest friendAddDecisionRequest = new FriendAddDecisionRequest(hostUserName, guestUserName, true);
        Response response = ConnectionUtil.makeConnection(friendAddDecisionRequest);
        if (response.getType() == ResponseType.FriendAddDecision) {
            FriendAddDecisionResponse friendAddDecisionResponse = (FriendAddDecisionResponse) response;
                JOptionPane.showMessageDialog(friendApplicationView, "添加好友成功！");
                friendApplicationView.listModel.remove(friendApplicationView.index);
        }
        else if(response.getType().equals(ResponseType.Error)) {
            ErrorResponse errorResponse=(ErrorResponse) response;
            JOptionPane.showMessageDialog(friendApplicationView, errorResponse.getResponseErrorCode().getMessage());
        }
    }

    public void disagree(String hostUserName, String guestUserName) {
        FriendAddDecisionRequest friendAddDecisionRequest = new FriendAddDecisionRequest(hostUserName, guestUserName, false);
        Response response = ConnectionUtil.makeConnection(friendAddDecisionRequest);
        if (response.getType() == ResponseType.FriendAddDecision) {
            FriendAddDecisionResponse friendAddDecisionResponse = (FriendAddDecisionResponse) response;
                JOptionPane.showMessageDialog(friendApplicationView, "已拒绝该好友申请");
                friendApplicationView.listModel.remove(friendApplicationView.index);
        }
        else if(response.getType().equals(ResponseType.Error)) {
            ErrorResponse errorResponse=(ErrorResponse) response;
            JOptionPane.showMessageDialog(friendApplicationView, errorResponse.getResponseErrorCode().getMessage());
        }
    }
}
